package com.example.controller;

import com.example.entity.JobEntity;
import com.example.service.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/jobs")
@CrossOrigin
public class JobController {

    @Autowired
    private JobService jobService;

    @PostMapping
    public ResponseEntity<JobEntity> addJob(@RequestBody JobEntity jobEntity) {
        try {
            return ResponseEntity.ok(jobService.addJob(jobEntity));
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PutMapping
    public ResponseEntity<Void> updateJob(@RequestBody JobEntity jobEntity) {
        try {
            jobService.updateJob(jobEntity);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @DeleteMapping("/{jobName}/{jobGroup}")
    public ResponseEntity<Void> deleteJob(@PathVariable String jobName, @PathVariable String jobGroup) {
        try {
            jobService.deleteJob(jobName, jobGroup);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{jobName}/{jobGroup}/pause")
    public ResponseEntity<Void> pauseJob(@PathVariable String jobName, @PathVariable String jobGroup) {
        try {
            jobService.pauseJob(jobName, jobGroup);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{jobName}/{jobGroup}/resume")
    public ResponseEntity<Void> resumeJob(@PathVariable String jobName, @PathVariable String jobGroup) {
        try {
            jobService.resumeJob(jobName, jobGroup);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/{jobName}/{jobGroup}")
    public ResponseEntity<JobEntity> getJob(@PathVariable String jobName, @PathVariable String jobGroup) {
        JobEntity job = jobService.getJob(jobName, jobGroup);
        return job != null ? ResponseEntity.ok(job) : ResponseEntity.notFound().build();
    }

    @GetMapping
    public ResponseEntity<List<JobEntity>> getAllJobs() {
        return ResponseEntity.ok(jobService.getAllJobs());
    }

    @GetMapping("/group/{jobGroup}")
    public ResponseEntity<List<JobEntity>> getJobsByGroup(@PathVariable String jobGroup) {
        return ResponseEntity.ok(jobService.getJobsByGroup(jobGroup));
    }
}